package com.koron.css2.newProjectCenter.impl.PubUpTemplate;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.css2.ServerInterface;
import com.koron.css2.newProjectCenter.bean.query.PubUpTemplateCostLinkQueryBean;
import com.koron.css2.newProjectCenter.bean.query.PubUpTemplateMaterialLinkQueryBean;
import com.koron.css2.newProjectCenter.bean.query.PubUpTemplateQueryBean;
import com.koron.css2.newProjectCenter.mapper.PubUpTemplateCostLinkMapper;
import com.koron.css2.newProjectCenter.mapper.PubUpTemplateMapper;
import com.koron.css2.newProjectCenter.mapper.PubUpTemplateMaterialLinkMapper;
import com.koron.css2.newProjectCenter.vo.PubUpTemplateCostLinkListVO;
import com.koron.css2.newProjectCenter.vo.PubUpTemplateListVO;
import com.koron.css2.newProjectCenter.vo.PubUpTemplateMaterialLinkListVO;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.List;

/**
 * 费用模板
 *
 * @author xs
 */
public class PubUpTemplateList implements ServerInterface {

    @Override
    @SuppressWarnings("rawtypes")
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {

            // 将入参转换为QueryBean
            PubUpTemplateQueryBean queryBean = JsonUtils.objectToPojo(req.getData(), PubUpTemplateQueryBean.class);
            // 获取Mapper实例
            PubUpTemplateMapper mapper = factory.getMapper(PubUpTemplateMapper.class);

            if (queryBean.getToDo() != null && queryBean.getToDo() == 2) {
                return updateOrSave(factory, mapper, userInfo, queryBean);
            }
            if (queryBean.getToDo() != null && queryBean.getToDo() == 3) {
                return delete(factory, mapper, queryBean);
            }
            if (queryBean.getToDo() != null && queryBean.getToDo() == 4) {
                return details(factory, mapper, userInfo, queryBean);
            }

            // 设置分页参数
            PageHelper.startPage(queryBean.getPage(), queryBean.getPageCount());
            // 执行SQL
            List<PubUpTemplateListVO> list = mapper.selecList(queryBean);

            // 输出分页结果
            MessageBean<PageInfo> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PageInfo.class);
            info.setData(new PageInfo<>(list));
            return info;
        } catch (Exception e) {
            factory.close(false);
            logger.error("查询失败" + e.getMessage(), e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "查询失败", null);
        }
    }

    /**
     * 更新或保存上传模板信息
     *
     * @param factory SessionFactory实例，用于获取Mapper
     * @param thisMapper 当前的Mapper实例，用于操作PubUpTemplate表
     * @param userInfo 用户信息，包含操作者的账号和名称等
     * @param queryBean 查询Bean，包含需要更新或保存的上传模板信息
     * @return 返回一个MessageBean，包含操作结果和受影响的行数
     */
    private MessageBean<?> updateOrSave(SessionFactory factory, PubUpTemplateMapper thisMapper, UserInfoBean userInfo, PubUpTemplateQueryBean queryBean) {
        // 检查queryBean中id是否为空，为空则表示需要创建新记录，否则更新现有记录
        if (StringUtils.isEmpty(queryBean.getId())) {
            // 设置创建信息
            queryBean.setCreateAccount(userInfo.getUserInfo().getAcount());
            queryBean.setCreateTime(new DateTime());
            queryBean.setCreateName(userInfo.getUserInfo().getName());
            queryBean.setId(Tools.getObjectId());
        } else {
            // 设置更新信息
            queryBean.setUpdateAccount(userInfo.getUserInfo().getAcount());
            queryBean.setUpdateTime(new DateTime());
            queryBean.setUpdateName(userInfo.getUserInfo().getName());
        }
        // 调用Mapper的更新或保存方法，执行数据库操作
        int num = thisMapper.updateOrSave(queryBean);
        if (num > 0) {
            // 如果操作成功，进一步处理材料链接和成本链接

            // 获取Mapper实例
            PubUpTemplateMaterialLinkMapper materialMapper = factory.getMapper(PubUpTemplateMaterialLinkMapper.class);
            // 删除模板相关的所有材料链接
            materialMapper.deleteByTemplateId(queryBean.getId());

            // 遍历并保存新的材料链接
            List<PubUpTemplateMaterialLinkQueryBean> MaterialLink = queryBean.getMaterialLink();
            for (PubUpTemplateMaterialLinkQueryBean ben : MaterialLink) {
                ben.setTemplateId(queryBean.getId());
                ben.setCreateTime(new DateTime());
                ben.setCreateName(userInfo.getUserInfo().getName());
                ben.setId(Tools.getObjectId());
                ben.setTenantId(userInfo.getCurWaterCode());
                if (ben.getStatus() == null) {
                    ben.setStatus(null);
                }
                if (ben.getSortNo() == null) {
                    ben.setSortNo(null);
                }
                materialMapper.updateOrSave(ben);
            }

            // 获取Mapper实例
            PubUpTemplateCostLinkMapper costMapper = factory.getMapper(PubUpTemplateCostLinkMapper.class);
            // 删除模板相关的所有成本链接
            costMapper.deleteByTemplateId(queryBean.getId());

            // 遍历并保存新的成本链接
            List<PubUpTemplateCostLinkQueryBean> costLink = queryBean.getTemplateCostLink();
            for (PubUpTemplateCostLinkQueryBean ben : costLink) {
                ben.setTemplateId(queryBean.getId());
                ben.setCreateTime(new DateTime());
                ben.setCreateName(userInfo.getUserInfo().getName());
                ben.setId(Tools.getObjectId());
                if (ben.getStatus() == null) {
                    ben.setStatus(0);
                }
                ben.setTenantId(userInfo.getCurWaterCode());

                if (ben.getSortNo() == null) {
                    ben.setSortNo(1);
                }
                costMapper.updateOrSave(ben);
            }
        }
        // 创建并返回操作结果信息
        MessageBean<Integer> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "修改成功", Integer.class);
        info.setData(num);
        return info;
    }

    private MessageBean<?> delete(SessionFactory factory, PubUpTemplateMapper thisMapper, PubUpTemplateQueryBean queryBean) {
        if (StringUtils.isEmpty(queryBean.getId())) {
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "主键id不能为空", null);
        }
        int num = thisMapper.delete(queryBean.getId());
        if (num > 0) {
            PubUpTemplateMaterialLinkMapper materialMapper = factory.getMapper(PubUpTemplateMaterialLinkMapper.class);
            materialMapper.deleteByTemplateId(queryBean.getId());
            PubUpTemplateCostLinkMapper costMapper = factory.getMapper(PubUpTemplateCostLinkMapper.class);
            costMapper.deleteByTemplateId(queryBean.getId());
        }

        MessageBean<Integer> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "删除成功", Integer.class);
        info.setData(num);
        return info;
    }

    /**
     * 获取模板详细信息
     * <p>
     * 此方法用于根据查询条件获取发布模板的详细信息，包括关联的材料和成本信息
     *
     * @param factory    SessionFactory实例，用于创建和管理数据库会话
     * @param thisMapper PubUpTemplateMapper实例，用于执行模板相关的数据库操作
     * @param userInfo   UserInfoBean实例，包含用户信息，目前在方法实现中未使用
     * @param queryBean  PubUpTemplateQueryBean实例，包含查询条件
     * @return 返回一个MessageBean实例，包含执行结果和模板详细信息
     */
    private MessageBean<?> details(SessionFactory factory, PubUpTemplateMapper thisMapper, UserInfoBean userInfo, PubUpTemplateQueryBean queryBean) {
        // 获取模板详细信息
        PubUpTemplateListVO vo = thisMapper.getdetails(queryBean.getId());
        // 如果模板信息不为空，则进一步获取关联的材料和成本信息
        if (vo != null) {
            // 获取与模板关联的材料信息
            PubUpTemplateMaterialLinkMapper materialMapper = factory.getMapper(PubUpTemplateMaterialLinkMapper.class);
            PubUpTemplateMaterialLinkQueryBean bean = new PubUpTemplateMaterialLinkQueryBean();
            bean.setTemplateId(queryBean.getId());
            List<PubUpTemplateMaterialLinkListVO> templateMaterial = materialMapper.selecList(bean);
            vo.setMaterialLink(templateMaterial);

            // 获取与模板关联的成本信息
            PubUpTemplateCostLinkQueryBean templateCostLink = new PubUpTemplateCostLinkQueryBean();
            templateCostLink.setTemplateId(queryBean.getId());
            PubUpTemplateCostLinkMapper costMapper = factory.getMapper(PubUpTemplateCostLinkMapper.class);
            List<PubUpTemplateCostLinkListVO> TemplateCostLinkList = costMapper.selecList(templateCostLink);
            vo.setTemplateCostLink(TemplateCostLinkList);
        }
        // 创建并返回包含执行结果和模板详细信息的消息豆
        MessageBean<PubUpTemplateListVO> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "查询成功", PubUpTemplateListVO.class);
        info.setData(vo);
        return info;
    }

}
